package design.mode.effective_java.chapter3.item14;

import java.util.Comparator;
import java.util.Objects;
import static java.util.Comparator.comparingInt;
import static java.util.Comparator.comparingDouble;
/**
 * @author ZhongMingde on 2021/8/11
 */

public class PhoneNumber implements Comparable<PhoneNumber>{
    private final short areaCode,prefix,lineNum;

    public PhoneNumber(short areaCode, short prefix, short lineNum) {
        this.areaCode = rangeCheck(areaCode,999,"area code");
        this.prefix = rangeCheck(prefix,999,"prefix");
        this.lineNum = rangeCheck(lineNum,9999,"lineNum");
    }



    private static short rangeCheck(int val, int max,String arg)  {
        if (val < 0 || val > max){
            throw new IllegalArgumentException(arg + ": " + val);
        }
        return (short) val;
    }


    @Override
    public boolean equals(Object o){
        if (o == this){
            return true;
        }
        if (!(o instanceof  PhoneNumber)){
            return false;
        }
        PhoneNumber pn = (PhoneNumber) o;
        return pn.lineNum == lineNum && pn.prefix == prefix && pn.areaCode == areaCode;
    }

    @Override
    public int hashCode(){
        int result = Short.hashCode(areaCode);
        result = 31 * result + Short.hashCode(prefix);
        result = 31 * result + Short.hashCode(lineNum);
        Objects.hash(areaCode,prefix,lineNum);
        return result;
    }

    @Override
    public String toString() {
        return String.format("%03d-%03d-%04d", areaCode, prefix, lineNum);
    }

    public static void main(String[] args) {
        System.out.println("Failed to connect to ");

    }

    /*@Override
    public int compareTo(PhoneNumber pn) {
        int result = Short.compare(areaCode,pn.areaCode);
        if (result == 0){
            result = Short.compare(prefix, pn.prefix);
            if (result == 0){
                result = Short.compare(lineNum, pn.lineNum);
            }
        }
        return result;
    }*/

    private static final Comparator<PhoneNumber> COMPARATOR = comparingInt(
            (PhoneNumber pn) -> pn.areaCode)
            .thenComparingInt(pn -> pn.prefix)
            .thenComparingInt(pn -> pn.lineNum);

    @Override
    public int compareTo(PhoneNumber pn) {
        return COMPARATOR.compare(this, pn);
    }
}
